/**
 * Created by huachuan on 2016/1/14.
 */
angular.module('otheruserhomecontrollers',[])
  //店铺详情的Controller
  .controller('OtherUserHomeCtrl',function($scope,$rootScope,$ionicPopup,$cordovaStatusbar,$ionicScrollDelegate,$cordovaFileTransfer,$state,$stateParams,$ionicActionSheet,UserHome,Home,Loading,MeAttend,Meeting,Toast,ENV,Storage,History,ShareServiceOther,ShareService){
      //当前登录的会员编号
      var memberId = '';
      var tolookMemberId = $stateParams['memberId'];
      $scope.picPath = ENV.picPath;
    $scope.isShareShow = ShareService.getIsShowShareWindow();//判断是否显示分享框
      $scope.showWhich = [true,false,false];

    //获取到手指下落的Index
    var index = 0;
    $scope.touchIndex = function(){
      for(i=0;i<$scope.showWhich.length;i++){
        if($scope.showWhich[i]){
          index = i;
          break;
        }
      }
    }
    //向左滑动
    $scope.swipeLeft = function(){
      var nextPage = index+1;
      if(nextPage<$scope.showWhich.length){
        $scope.showWhich = [false,false,false];
        $scope.showWhich[nextPage] = true;
        if(nextPage==0){
          showAttendListFun();
        }else if(nextPage==1){
          showHomeListFun();
        }if(nextPage==2){
          showMeetingListFun();
        }
      }
    }
    //向右滑动
    $scope.swipeRight = function(){
      var prePage = index-1;
      if(prePage>=0){
        $scope.showWhich = [false,false,false];
        $scope.showWhich[prePage] = true;
        if(prePage==0){
          showAttendListFun();
        }else if(prePage==1){
          showHomeListFun();
        }if(prePage==2){
          showMeetingListFun();
        }
      }
    }

    var firstIn = true;
    //每一次进入获取到用户的信息
    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.loginMemberId = memberId = Storage.get('member').member_id;
      if(firstIn){
        Loading.showLoading();
        firstIn = false;
      }
      UserHome.getOtherUserInfo(memberId,tolookMemberId);
      UserHome.getUserAttendList(memberId,tolookMemberId);
      //当页面不是第一次进入的时候，重新加载酒窝的点赞状态，收藏状态，评论数
      if($scope.showWhich[1]&&$scope.userHomeList!=undefined && $scope.userHomeList.length!=0){
        searchList = [];
        for(i=0;i<$scope.userHomeList.length;i++){
          search = {
            mh_id:$scope.userHomeList[i].mh_id,
            member_id:memberId
          }
          searchList.push(search);
        }
        Home.getCurrentHomeInfo(searchList);//获取
      }
      if($scope.showWhich[2]&&$scope.userMeetingList!=undefined&&$scope.userMeetingList.length>0){
        searchList = [];
        for(i=0;i<$scope.userMeetingList.length;i++){
          search = {
            mm_id:$scope.userMeetingList[i].mm_id,
            member_id:memberId
          }
          searchList.push(search);
        }
        if(searchList.length>0){
          Meeting.getCurrentMeetingInfo(searchList);
        }
      }
    })
    //局部刷新用户的约局列表
    $scope.$on('Meeting.getCurrentMeetingInfoUpdated',function(){
      var result = Meeting.getCurrentInfo();
      for(i=0;i<$scope.userMeetingList.length;i++){
        for(j=0;j<result.length;j++){
          if($scope.userMeetingList[i].mm_id==result[j].mm_id){
            $scope.userMeetingList[i].mm_comment_num = result[j].mm_comment_num;
            $scope.userMeetingList[i].lmeetStatus = result[j].lmeetStatus;
            $scope.userMeetingList[i].mcmeetStatus = result[j].mcmeetStatus;
          }
        }
      }
    });
    //局部刷新酒窝的点赞信息
    $scope.$on('Home.currentHomeInfoeUpdated',function(){
      var result = Home.getCurrentJson().currentInfo;
      for(i=0;i<result.length;i++){
        for(j=0;j<$scope.userHomeList.length;j++){
          if(result[i].mh_id==$scope.userHomeList[j].mh_id){
            $scope.userHomeList[j].lhomeStatus = result[i].lhomeStatus;
            $scope.userHomeList[j].mchomeStatus = result[i].mchomeStatus;
            $scope.userHomeList[j].mh_comment_num = result[i].mh_comment_num;
            $scope.userHomeList[j].mh_praise_num = result[i].mh_praise_num;
          }
        }
      }
    });

    $scope.$on('UserHome.memberInfoUpdated',function(){
      Loading.hideLoading();
        $scope.lookMember = UserHome.getMemberInfoJson();
    });
      /*************显示我的关注********/
      $scope.showAttendList = function(){
        showAttendListFun();
      }
      showAttendListFun = function(){
        $ionicScrollDelegate.scrollTop();
        $scope.showWhich = [true,false,false];
        UserHome.getUserAttendList(memberId,tolookMemberId);
      }
      /*$scope.$on('$ionicView.loaded', function () {
      Loading.showLoading();

      })*/
      $scope.$on('UserHome.userAttendMemberListUpdated',function(){
        $scope.userAttendMemberList = UserHome.getUserAttendListJson().attendMemberList;
        Loading.hideLoading();
      });
      //关注会员
    var focusIndex = '';
    $scope.foucsMember = function(toAttendMemberId,index){
      Loading.showLoading();
      MeAttend.focusFriend(memberId,toAttendMemberId);
      focusIndex = index;
    }
    //var saveNoAttendMemberId = '';
    $scope.noFoucsMember = function(toAttendMemberId,index){
        $ionicPopup.confirm({
          template: '<p style="text-align: center;font-size:16px">确定要取消关注吗？</p>',
          cancelText: '继续关注',
          okText: '取消关注',
          okType: 'hd-red-btn',
          cancelType: 'cancel-esc-btn'
        }).then(function (res) {
          if (res) {
            //取消对该会员的关注
            focusIndex = index;
            Loading.showLoading();
            MeAttend.focusFriend(memberId,toAttendMemberId);
          }
        });
    }
    //关注或者取消关注时访问网络成功返回的信息
    $scope.$on('MeAttend.focusFriendUpdated',function(){
      Loading.hideLoading();
      var result = MeAttend.getFocusFriendMsgJson();
      if(result.isAttendMsg!='网络异常，请稍后再试'){
          if(focusIndex==undefined){
            $scope.lookMember.isAttend = result.isAttend;
          }else{
            $scope.userAttendMemberList[focusIndex].isAttend = result.isAttend;
          }
      }
      Toast.showMessage(result.isAttendMsg);
    });
    /*************显示我的关注结束********/


      /***************显示我的酒窝*********/
      var firstInUserHome = true;
      $scope.showHomeList = function(){
        showHomeListFun();
      }
    showHomeListFun = function(){
      $ionicScrollDelegate.scrollTop();
      $scope.showWhich = [false,true,false];
      if(firstInUserHome){
        Loading.showLoading();
        firstInUserHome = false;
      }
      UserHome.getUserHomeList(memberId,tolookMemberId);
    }
    //加载更多
      $scope.loadMore = function(){
        if($scope.showWhich[1]){
          UserHome.getMoreUserHomeList(memberId,tolookMemberId);
        }else if($scope.showWhich[2]){
          UserHome.getMoreUserMeetingList(memberId,tolookMemberId);
        }

      }
      //用户酒窝是否有下一页
      $scope.homeHasNextPage = function(){
            return UserHome.homeHasNextPage();
      }
      //用户约局是否有下一页
      $scope.meetingHasNextPage = function(){
        return UserHome.meetingHasNextPage();
      }

      $scope.$on('UserHome.userHomeListUpdated',function(){
        Loading.hideLoading();
        $scope.$broadcast('scroll.infiniteScrollComplete');
        $scope.userHomeList = UserHome.getUserHomeListJson();

      });
    //收藏酒窝
    var collectorLikeHomeIndex = '';
    $scope.collectHome =function(index,mhId){
      Loading.showLoading();
      Home.collectHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.collectHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getCollectHomeMsgJson();
      Toast.showMessage(result.mchomeMsg);
      $scope.userHomeList[collectorLikeHomeIndex].mchomeStatus = result.mchomeStatus;
    });
    //点赞酒窝
    $scope.likeHome =function(index,mhId){
      Loading.showLoading();
      Home.likeHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.likeHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getLikeHomeMsgJson();
      Toast.showMessage(result.lhomeMsg);
      $scope.userHomeList[collectorLikeHomeIndex].lhomeStatus = result.lhomeStatus;
    });
    //酒窝显示大图
    $scope.showBigImage= function(homeIndex,picIndex){
      var items = [];
      var lookImageList = $scope.userHomeList[homeIndex].picSrc;
      var pswpElement = document.querySelectorAll('.pswp')[0];
      for(i=0;i<lookImageList.length;i++){
        var temp = {
          src:$scope.picPath+"big_"+lookImageList[i].src,
          w:lookImageList[i].w,
          h:lookImageList[i].h
        };
        items.push(temp);
      }
      var options = {
        index: picIndex,
        history: false,
        focus: false,
        loop: false,
       /* pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
      //$cordovaStatusbar.hide();
    }
    //长按下载
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = targetPath = cordova.file.externalRootDirectory+"winelife/winelife_home_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
       buttons: [
       {text: '保存到手机相册'}
       ],
       cancelText: '取消',
       buttonClicked: function (index) {
       if(index==0){
         if(ionic.Platform.isIOS()){
           Loading.showLoading();
         }
       $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
       .then(function(result) {
       Toast.showMessage("保存成功");
       }, function(err) {
           Toast.showMessage("保存成功");
       }, function (progress) {
       });
       }
       return true;
       }
       });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
     // $cordovaStatusbar.show();
    }
    //显示酒窝分享框
    $scope.showHomeShare = function(mh_id){
      ShareServiceOther.showShareWindow(mh_id,"home");
    };
    /***************显示我的酒窝结束*********/
    /**************显示我的约局************/
      var collectIndex = '';//收藏的索引
      var likeIndex = '';//点赞的索引
      var firstInUserMeeting = true;
      $scope.showMeetingList = function(){
        showMeetingListFun();
      }
    showMeetingListFun = function(){
      $scope.showWhich = [false,false,true];
      if(firstInUserMeeting){
        Loading.showLoading();
        firstInUserMeeting = false;
      }
      UserHome.getUserMeetingList(memberId,tolookMemberId);
    }
    $scope.$on('UserHome.userMeetingListUpdated',function(){
      $scope.userMeetingList = UserHome.getUserMeetingListJson();
      Loading.hideLoading();
    });

    //收藏
    $scope.collectMeeting = function(index,mmId){
      Loading.showLoading();
      collectIndex = index;
      Meeting.collectMeeting(memberId,mmId);
    };
    //网络访问成功后
    $scope.$on('Meeting.collectMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getCollectJson();
      $scope.userMeetingList[collectIndex].mcmeetStatus = result.mcmeetStatus;
      Toast.showMessage(result.mcmeetMsg);
      collectIndex='';
    })
    //点赞
    $scope.likeMeeting = function(index,mmId){
      Loading.showLoading();
      likeIndex = index;
      Meeting.likeMeeting(memberId,mmId);
    }
    //网络访问成功后
    $scope.$on('Meeting.likeMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getLikeJson();
      $scope.userMeetingList[likeIndex].lmeetStatus = result.lmeetStatus;
      Toast.showMessage(result.lmeetMsg);
      likeIndex='';
    })

    //显示约局分享框
    $scope.showMeetingShare = function(mm_id){
      ShareServiceOther.showShareWindow(mm_id,"meeting");
    };

    /*************显示我的约局结束************/
      //返回
      $scope.goback = function(){History.goback();};

    //点击头像跳转到用户的个人信息
    $scope.go2MemberInfo = function(memberId){
      $state.go('member-data',{'memberId':memberId});
    }


  });
